﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CommonClasses.Utility
{
    /// <summary>
    /// Фильтр очереди сообщений, который отслеживает сообщение WM_KEYDOWN
    /// </summary>
    public class KeyPressMessageFilter : IMessageFilter
    {
        private const int WM_KEYDOWN = 0x0100;

        private List<KeyPressEventHandler> handlers;

        public KeyPressMessageFilter()
        {
            handlers = new List<KeyPressEventHandler>();
        }

        public void Subscribe(KeyPressEventHandler handler)
        {
            if (!handlers.Contains(handler))
                handlers.Add(handler);
        }

        public void DetachSubscription(KeyPressEventHandler handler)
        {
            if (handlers.Contains(handler))
                handlers.Remove(handler);
        }

        #region IMessageFilter Members

        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == WM_KEYDOWN)
            {
                var handled = false;
                foreach (var handler in handlers)
                {
                    var args = new KeyPressEventArgs((char)m.WParam.ToInt32());
                    handler(null, args);
                    handled |= args.Handled;
                }
                return handled;
            }
            return false;
        }

        #endregion
    }
}
